﻿using Castle.Core;
using Domain.Base;
using Domain.Entity;
using DtoFw;
using DtoFw.Query;
using DtoFw.Result;
using Microsoft.AspNetCore.Mvc;
using Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using Util;

namespace Service
{
    public class MainUserService
    {
        private readonly MainUserRepository rep_mainUser;
        private readonly MainUserMapRoleRepository rep_mainUserMap;
        private readonly MainRoleRepository rep_mainRole;
        private readonly MainOrganRepository _mainOrganRepository;
        public MainUserService(MainUserRepository mainUser, MainUserMapRoleRepository mainUserMap, 
            MainRoleRepository mainRole, MainOrganRepository mainOrganRepository)
        {
            rep_mainUser = mainUser;
            rep_mainUserMap = mainUserMap;
            rep_mainRole = mainRole;
           _mainOrganRepository = mainOrganRepository;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public BaseResult Post(UserInfoAddInfo info)
        {
            long? userid = 0;
            BaseResult baseResult = new BaseResult();
            var newinfo = rep_mainUser.Get(new BaseQuery(),
                               t => t.Where(m => (m.UserNo == info.UserNo || m.PoliceNo == info.PoliceNo) && !m.IsDeleted));
            if (newinfo != null)
                return BaseResult.Failure("当前账号或警号已存在");
            MainUserEntity user = Util.AutoMapperExtension.MapTo<UserInfoInfo, MainUserEntity>(info);
            user.Salt = RandomHelper.RandCode(6);
            user.Pwd = SecurityHelper.GetPwd(info.Pwd, user.Salt);
            user.CreatorId = info.UserId;
            user.CreateTime = DateTime.Now;
            user.Creator = user.Modifyer = info.CurrentUser.UserName;
            userid = rep_mainUser.Save(user)?.Id;
            MainUserMapRoleEntity userMapRole = new MainUserMapRoleEntity();
            userMapRole.UserId = userid.Value;
            userMapRole.RoleId = info.RoleId;
            rep_mainUserMap.Save(userMapRole);
            return baseResult;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public BaseResult Put(UserInfoEditInfo info)
        {
            BaseResult baseResult = new BaseResult();
            var user = rep_mainUser.Get(new BaseQuery() { Id = info.Id });
            if (user == null)
                return new BaseResult() { Success = false, Msg = "获取用户失败" };
            user = Util.AutoMapperExtension.MapTo<UserInfoEditInfo, MainUserEntity>(info, user);
            user.ModifyerId = info.UserId;
            user.ModifyerTime = DateTime.Now;
            user.Modifyer = info.UserName;
            rep_mainUser.Save(user);
            if (info.RoleId > 0)
            {
                var userMapRole = rep_mainUserMap.Get(new BaseQuery(),
                    t => t.Where(x => x.UserId == user.Id));
                userMapRole.RoleId = info.RoleId;
                rep_mainUserMap.Save(userMapRole);
            }
            return baseResult;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public BaseGenericResult<long> SaveAdd(UserInfoAddInfo info)
        {
            long? userid = 0;
            BaseGenericResult<long> baseResult = new BaseGenericResult<long>();
            var newinfo = rep_mainUser.Get(new BaseQuery(),
                              t => t.Where(m => m.UserNo == info.PoliceNo));
            if (newinfo != null)
            {
                baseResult.Msg = "添加失败，当前账号已存在";
                baseResult.Success = false;
                return baseResult;
            }
            MainUserEntity user = Util.AutoMapperExtension.MapTo<UserInfoAddInfo, MainUserEntity>(info);
            user.Salt = RandomHelper.RandCode(6);
            user.Pwd = SecurityHelper.GetPwd(info.Pwd, user.Salt);
            user.CreatorId = user.ModifyerId = info.UserId;
            user.CreateTime = user.ModifyerTime = DateTime.Now;
            user.Creator = user.Modifyer = info.UserName;
            userid = rep_mainUser.Save(user)?.Id;
            if (userid < 1)
            {
                baseResult.Msg = "添加失败，系统异常";
                baseResult.Success = false;
                return baseResult;
            }
            MainUserMapRoleEntity userMapRole = new MainUserMapRoleEntity();
            userMapRole.UserId = userid.Value;
            userMapRole.RoleId = info.RoleId;
            rep_mainUserMap.Save(userMapRole);
            baseResult.Data = user.Id;
            return baseResult;
        }
        /// <summary>
        /// 获取用户对象
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public BaseGenericResult<UserInfoEditInfo> Get(long id)
        {
            var rep = new BaseGenericResult<UserInfoEditInfo>();
            if (id < 1)
            {
                rep.Msg = "参数异常";
                rep.Success = false;
                return rep;
            }
            var info = rep_mainUser.Get(new BaseQuery() {Id=id });
            if (info == null)
            {
                rep.Msg = "用户信息不存在";
                rep.Success = false;
                return rep;
            }
            rep.Data = Util.AutoMapperExtension.MapTo<MainUserEntity, UserInfoEditInfo>(info);
            var roleinfo = rep_mainUserMap.Get(new BaseQuery(), t => t.Where(m => m.UserId == info.Id));
            rep.Data.RoleId = (roleinfo?.RoleId).Value;
            rep.Msg = "成功";
            rep.Success = true;
            return rep;
        }
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="query">条件</param>
        /// <returns></returns>
        public BaseGenericResult<Pager<UserinfoResult>> QueryList(UserInfoQuery query,string organid)
        {
            BaseGenericResult<Pager<UserinfoResult>> baseResult = new BaseGenericResult<Pager<UserinfoResult>>();
            baseResult.Data = new Pager<UserinfoResult>();
            var pager = rep_mainUser.GetPagerList(query, organid);
            if (pager.TotalCount > 0)
            {
                var usermaproles = rep_mainUserMap.Query(new BaseQuery())?.ToList();
                var roles = rep_mainRole.Query(new BaseQuery());
                baseResult.Data.TotalCount = pager.TotalCount;
                baseResult.Data.Data = Util.AutoMapperExtension.MapTo<MainUserEntity, UserinfoResult>(pager.Data);
                var ids = baseResult.Data.Data.Select(i => i.Id).ToList();
                foreach (var item in baseResult.Data.Data)
                {
                    var usermaprole = usermaproles.FirstOrDefault(t => t.UserId == item.Id);
                    if (usermaprole == null)
                        continue;
                    item.RoleId = usermaprole.RoleId;
                    item.OrganName = _mainOrganRepository.Get(new BaseQuery(), x => x.Where(m => m.Id == item.OrgId))?.Name;
                    item.RoleName = roles.First(t => t.Id == usermaprole.RoleId)?.Name;
                }
            }
            return baseResult;
        }
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="query">条件</param>
        /// <returns></returns>
        public BaseGenericResult<Pager<UserinfoResult>> QueryListByOrganId(long organid)
        {
            BaseGenericResult<Pager<UserinfoResult>> baseResult = new BaseGenericResult<Pager<UserinfoResult>>();
            baseResult.Data = new Pager<UserinfoResult>();
            var lst = rep_mainUser.Query(new BaseQuery(), t=>t.Where(v=>v.OrgId == organid)).ToList();

            var pager = new Pager<MainUserEntity>() { TotalCount = lst.Count, Data = lst };

            if (pager.TotalCount > 0)
            {
                var usermaproles = rep_mainUserMap.Query(new BaseQuery())?.ToList();
                var roles = rep_mainRole.Query(new BaseQuery());
                baseResult.Data.TotalCount = pager.TotalCount;
                baseResult.Data.Data = Util.AutoMapperExtension.MapTo<MainUserEntity, UserinfoResult>(pager.Data);
                var ids = baseResult.Data.Data.Select(i => i.Id).ToList();
                foreach (var item in baseResult.Data.Data)
                {
                    var usermaprole = usermaproles.FirstOrDefault(t => t.UserId == item.Id);
                    if (usermaprole == null)
                        continue;
                    item.RoleId = usermaprole.RoleId;
                    item.OrganName = _mainOrganRepository.Get(new BaseQuery(), x => x.Where(m => m.Id == item.OrgId))?.Name;
                    item.RoleName = roles.First(t => t.Id == usermaprole.RoleId)?.Name;
                }
            }
            return baseResult;
        }
        public List<MainUserEntity> QueryAll(DateTime? latest)
        {
            if (latest == null)
            {
                return rep_mainUser.Query(v => v.IsDeleted == false);
            }
            else
            {
                return rep_mainUser.Query(v => v.ModifyerTime >= latest.Value);
            }
        }

        public List<MainUserEntity> QueryByOrgId(long orgId)
        {
            return rep_mainUser.Query(v => v.IsDeleted == false && v.OrgId == orgId);
        }

        public MainUserEntity Query(long userId)
        {
            return rep_mainUser.Query(v=>v.Id == userId).FirstOrDefault();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public BaseResult PutPassWord(PutPwdQuery query)
        {
            var user = rep_mainUser.Get(new BaseQuery() { Id = query.UserId });
            if (user == null)
                return BaseResult.Failure("用户不存在");
            if (user.Pwd != SecurityHelper.GetPwd(query.OldPwd, user.Salt))
                return BaseResult.Failure("旧密码不正确");
            user.Salt = RandomHelper.RandCode(6);
            user.Pwd = SecurityHelper.GetPwd(query.Pwd, user.Salt);
            user.ModifyerId = query.UserId;
            user.ModifyerTime = DateTime.Now;
            if (rep_mainUser.Save(user).Id > 0)
                return BaseResult.Succeed();
            return BaseResult.Failure("密码修改失败");
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public BaseResult RestPassWord(RestPwdQuery query)
        {
            string MdSalt = RandomHelper.RandCode(6);
            string PassWord = SecurityHelper.GetPwd(query.Pwd, MdSalt);
            var users = rep_mainUser.Query(new BaseQuery()
            {
                Ids = query.UserIds
            })?.ToList();
            users.ForEach(t =>
            {
                t.Pwd = PassWord;
                t.Salt = MdSalt;
                rep_mainUser.Save(t);
            });
            return new BaseResult();
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public BaseResult Delete(DeleteDto query)
        {
            var result = rep_mainUser.DeleteBatch(new BaseOperate() { Ids = query.Ids, ModifyerId = query.UserId, Modifyer = query.UserName });
            if (result > 0)
                return BaseResult.Succeed();
            return BaseResult.Failure("删除失败");
        }


        public BaseResult ImportUsers(List<ImportUserEntity> users)
        {
            var depts = users.GroupBy(v => new { v.deptId,v.deptName });
            foreach (var _dept in depts)
            {
                var deptInf = _mainOrganRepository.Query(v => v.ComNo == _dept.Key.deptId).FirstOrDefault();
                if(deptInf == null)
                {
                    deptInf = new MainOrganEntity();
                    deptInf.CName = deptInf.Name = _dept.Key.deptName;
                    deptInf.ComNo = _dept.Key.deptId;
                    deptInf.SuperiorId = 0;
                    deptInf.Used = 1;
                    deptInf.ModifyerTime = deptInf.CreateTime = DateTime.Now;
                    deptInf.Modifyer = deptInf.Creator = "sys";
                    deptInf.ModifyerId = deptInf.CreatorId = 0;
                    deptInf.Id = _mainOrganRepository.Insert(deptInf);
                }
                foreach (var _u in _dept)
                {
                    var newinfo = rep_mainUser.Get(new BaseQuery(), t => t.Where(m => (m.UserNo == _u.policeNo || m.PoliceNo == _u.policeNo) && !m.IsDeleted));
                    if (newinfo != null)
                        continue;
                    MainUserEntity user = new MainUserEntity();
                    user.Salt = "0mcYps";
                    user.Pwd = "cfc3d5c57709c297ca273203cde81ed3";
                    user.Name = _u.username;
                    user.Sex = _u.sex == "男" ? 1 : 2;
                    user.PoliceNo = _u.policeNo;
                    user.UserNo = _u.policeNo;
                    user.OrgId = deptInf.Id;
                    user.CardType = 1;
                    user.CardNo = _u.userId;
                    user.PostName = _u.jobName;
                    user.EmpStatus = 1;
                    user.UserStatus = 1;
                    user.ModifyerTime = user.CreateTime = DateTime.Now;
                    user.Modifyer = user.Creator = "sys";
                    user.ModifyerId = user.CreatorId = 0;
                    user.IsDisable = 1;
                    rep_mainUser.Save(user);
                }
            }
            return BaseResult.Succeed();
        }
    }
}
